import axios ,{type AxiosResponse} from "axios";
import router from "@/router";
import Cookie from "js-cookie";
import Qs from "qs";
import { ElMessage } from 'element-plus'

declare interface typeResponse extends AxiosResponse {
    errno: number
    errmsg: string
}

let host =''
if ("development" === import.meta.env.MODE) {
    //是否为开发判断
    host = "http://192.168.1.188:8080"; //上线前
} else {
    host = "http://zxwyit.cn:8080"; //上线后
}
let baseURL = host+'/m.api'
// 创建axios实例
const instance = axios.create({
    baseURL,
    headers: { "content-type": "application/x-www-form-urlencoded" }
})
// 请求拦截
instance.interceptors.request.use(
    (config) => {
        let token = Cookie.get('token');
        if (token) {    // token存放到请求头中            
            (config.headers as { AdminToken: string })['AdminToken'] = token;
        }
        return config
    }, (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
)


// 响应拦截
instance.interceptors.response.use(
    (res) => {
        let { errno, data, errmsg } = res.data
        console.log('res===>', data)
        //判断token是否已过期
        if (10006 == errno) {
            router.replace({ path: "/login" });
            // 无痛刷新
            
        } else if (200 !== errno) {
            ElMessage.error(errmsg);
        }
        return Promise.resolve(res.data)    
    }, (error) => {
        const {
            response
        } = error;
        return Promise.reject(response);
    }
)
export const get =function (params:object): Promise<typeResponse> {
    return instance.get("", { params })
}


export const post = function(data: object, params?: object): Promise<typeResponse> {
    return instance.post("", Qs.stringify(data), { params })
}

/**
 * 上传
 * @param data 图片数据 
 * @returns
 */
export const upload = function(data: object): Promise<typeResponse> {
    return instance.post("../upload/admin", data)//../表示上级目录，比较巧妙
}

export default instance

